#include <stdio.h>
#include <unistd.h>
#include <iostream>

#include "tools.h"
#include "servicedao_file_impl.h"

vector<Department*>& ServiceDaoFileImpl::load(vector<Department*>& departments)
{
	
	FILE* frp = fopen("services.dat","rb");
	if(frp == NULL)
	{
		return departments;
	}
	departments.clear();

	int ret = 1;
	while(ret)
	{	
		char buf[255] = {};
		Department* department = new Department;
		ret = fread(buf,sizeof(buf),1,frp);
		
		if(ret > 0)
		{
			int id,total;
			char name[20];

			sscanf(buf,"%d %s %d",&id,name,&total);
			department->setID(id);
			department->setTotal(total);
			department->setName(name);


			department->get_employee_vector().clear();
			
			for(int i=0; i<department->getTotal(); i++)
			{
				Employee* employee = new Employee;
				if(0 < fread(employee,sizeof(Employee),1,frp))
				{
					department->get_employee_vector().push_back(employee);
				}
			}
			departments.push_back(department);
		}	
		
	}

	fclose(frp);
	return departments;
}

void ServiceDaoFileImpl::save(vector<Department*>& departments)
{
	FILE* fwp = fopen("services.dat","wb");
	if(fwp == NULL)
	{
		perror("fopen");
		return;
	}
	
	for(unsigned int i=0; i<departments.size(); i++)
	{
		char buf[255]  = {};

		sprintf(buf,"%d %s %d",departments.at(i)->getDept_id(),departments.at(i)->getDept_name(),departments.at(i)->getTotal());
		fwrite(buf,sizeof(buf),1,fwp);

		
		for(unsigned int j=0; j<departments.at(i)->get_employee_vector().size(); j++)
		{
			fwrite(departments.at(i)->get_employee_vector().at(j),sizeof(Employee),1,fwp);
		}

	}
/*
	rewind(fwp);
	Department* department = new Department;
	fread(department,sizeof(Department),1,fwp);

	cout<<department->getDept_id()<< " "<<department->getDept_name()<<" "<< department->getTotal()<<endl;
	cout << "du" << endl;
	getchar();
	getchar();
*/
	fclose(fwp);
}